<template>
	<view class="balance-detail">
		<view class="month-section" v-for="(monthGroup, index) in groupedRecords" :key="index">
			<view class="month-header">{{ monthGroup.month }}</view>
			<view class="record-item" v-for="(record, recordIndex) in monthGroup.records" :key="recordIndex">
				<view class="record-info">
					<view class="record-name">{{ record.name }}</view>
					<view class="record-time">{{ record.time }}</view>
				</view>
				<view class="record-amount">{{ record.amount > 0 ? '+' : '' }}{{ record.amount }}</view>
			</view>
		</view>
	</view>
</template>

<script>
import {request} from '../../../utils/request';

export default {
	data() {
		return {
			records: []
		};
	},
	onLoad() {
		// 在组件挂载时自动请求数据
		this.getBalanceDetails();
	},
	methods: {
		async getBalanceDetails() {
			try {
				const res = await request({
					url: '/User/balanceDetails?page=1&limit=10',
					method: 'GET'
				});
				if (res.code === 1) {
					// 遍历所有月份数据并合并details
					this.records = res.data.list.flatMap(monthItem =>
						monthItem.details.map(item => ({
							name: item.memo,  
							time: item.createtime,  
							amount: Number(item.money),  
							month: monthItem.month  
						}))
					);
				}
			} catch (error) {
				console.error('获取余额明细失败', error);
			}
		}
	},
	computed: {
		groupedRecords() {
			const groups = {};
			this.records.forEach(record => {
				if (!groups[record.month]) {
					groups[record.month] = {
						month: record.month,
						records: []
					};
				}
				groups[record.month].records.push(record);
			});
			// 按月份排序（最新的月份在前）
			return Object.values(groups).sort((a, b) => new Date(b.month) - new Date(a.month));
		}
	}
};
</script>

<style lang="scss" scoped>
.balance-detail {
	padding: 16px;
	background-color: #F2F3F8;
	/* 设置整个页面背景色 */
	min-height: 100vh;

	/* 确保背景色充满整个屏幕高度 */
	.month-section {
		margin-bottom: 16px;
		background-color: #FFFFFF;
		border-radius: 35rpx;
		padding: 0 16px;

		.month-header {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 36rpx;
			color: #0E1C37;
			margin-bottom: 5rpx;
			padding-top: 32rpx;
			padding-bottom: 25rpx;
			border-bottom: 1rpx solid #EEF2F3;
		}

		.record-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12px 0;
			border-bottom: 1px solid #f0f0f0;

			.record-info {
				.record-name {
					font-family: Source Han Sans CN;
					font-weight: 500;
					font-size: 26rpx;
					color: #0E1C37;
					margin-bottom: 4px;
				}

				.record-time {
					font-family: Source Han Sans CN;
					font-weight: 400;
					font-size: 22rpx;
					color: #888B9A;
				}
			}

			.record-amount {
				font-family: Source Han Sans CN;
				font-weight: 500;
				font-size: 26rpx;
				color: #0E1C37;
			}
		}
	}
}
</style>